package core

import (
	"fmt"
	"log"
	"net/http"
	"strconv"

	"golang.org/x/net/websocket"
)

func CmdList(w http.ResponseWriter, r *http.Request) {
	var res Responser = new(Response)
	res.SetResponseWriter(w)

	defer func() {
		if r := recover(); r != nil {
			msg := fmt.Sprintf("获取列表失败（%s）", r)
			log.Printf(msg)
			res.AddError(501002, msg)
			res.AddErrorList(ErrorDeployError)
			res.InternalServerError(ErrorInternalServerError)
		}
	}()

	list := make([]map[string]interface{}, 0)
	config := GetConfig()
	for _, v := range config {
		list = append(list, v["label"])
	}
	res.Success(list)
}

func Deploy(ws *websocket.Conn) {
	msg := make([]byte, 512)
	n, err := ws.Read(msg)
	if err != nil {
		log.Fatal(err)
	}
	index, _ := strconv.Atoi(string(msg[:n]))
	err = CommandRun(index, ws)

	var ret string
	if err != nil {
		ret = fmt.Sprintf("\r\nend部署失败（%s）\r\n", err)
	} else {
		ret = "\r\nend部署完成\r\n"
	}

	m, err := ws.Write([]byte(strconv.Itoa(index) + ":" + ret))
	if err != nil {
		log.Fatal(err)
	}
	log.Print(m)
}
